/**
 * Project: apollo-base-dal
 * 
 * File Created at 2016年5月9日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.dal.jdbc.mapper;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.JdbcUtils;

import com.dx.pf.dal.cache.DalCache;
import com.dx.pf.dal.cache.EntryInfo;

/** 
* @ClassName: BeanPropertyAccessResultSetExtractor 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2016年5月9日 下午12:14:37 
* @version V1.0 
*/
public class BeanAccessResultSetExtractor<T> implements ResultSetExtractor<T> {

	/**列参数对应的参数属性*/
	private EntryInfo entryInfo = null;
	/** 列参数对应的参数属性 */
	private Map<String, PropertyDescriptor> mappedFields;

	/** 映射类 */
	private Class<T> mappedClass;

	
	public BeanAccessResultSetExtractor(Class<T> mappedClass){
		initialize(mappedClass);
	}
	
	protected void initialize(Class<T> mappedClass) {
		this.mappedClass = mappedClass;
		this.mappedFields = new HashMap<String, PropertyDescriptor>();
		this.entryInfo = DalCache.getInstance().getEntryPropertyMap(mappedClass);
		this.mappedFields = entryInfo.getFieldNamePropertyDesc();
	}
	
	@Override
	public T extractData(ResultSet rs) throws SQLException, DataAccessException {
		T mappedObject = BeanUtils.instantiate(this.mappedClass);
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		for (int index = 1; index <= columnCount; index++) {
			String column = JdbcUtils.lookupColumnName(rsmd, index);// 获得当前列名称
			PropertyDescriptor pd = mappedFields.get(column);
			if (pd != null) {
				Object value = getColumnValue(rs, index, pd);
				if (value != null) {
					bw.setPropertyValue(pd.getName(), value);// 设置值
				}
			}
		}
		return mappedObject;
	}

	/**
	 * @Description: 通过JDBCUtil返回值 
	 * @param rs 
	 * @param index 
	 * @param
	 * pd @return @throws SQLException Object @throws
	 */
	protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
		return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
	}
}
